package com.snails.net.retrofit.interceptor;

import android.text.TextUtils;

import com.snails.logger.Logger;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 网络请求失败重连方案
 * 使用方法：在请求header中通过设置retry-count，来设置重连次数
 *
 * @author lawrence
 * @date 201-04-11
 */
public class RetryInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        // 重试次数
        int retry_count = 0;
        // 得到 请求头中的  重置次数
        final String retryStr = request.header(RetrofitConstant.RETRY_COUNT);
        if (!TextUtils.isEmpty(retryStr)) {
            try {
                retry_count = Integer.parseInt(retryStr.trim());
            } catch (NumberFormatException e) {
                retry_count = 0;
            }
        }

        Response response = null;
        // 已重试次数
        int retry_num = 0;
        do {
            Logger.d("网络重连：Retry-Count=" + retry_count + " Retry-Num=" + retry_num
                    + "\n" + "url => " + request.url());

            if (retry_num > 0) {
                request = request.newBuilder().build();
            }

            response = chain.proceed(request);
        } while (!response.isSuccessful() && retry_num++ < retry_count);
        return response;
    }

}

